require 'java'

class FieldToPropertyMap
  attr_accessor :node_map, :format_config, :property_map, :index_map

  def initialize
    @node_map={}
    @property_map={}
    @index_map={}
  end

  def load_config(file_name)
    self.format_config= YAML.load_file file_name
  end

  def data=(data_string)
    @data=data_string.split "\t"
  end

  def data
    @data
  end

  def property_map
    result_map={}
    property_specs = self.format_config['fields'].select {|f| f.has_key? 'property'}
    property_specs.each do |spec|
      clazz = spec['class']
      property_name = spec['property']
      string_value = self.data[spec['position']]
      case clazz
      when 'integer'
        result_map[property_name]=java.lang.Long.new(string_value.to_i)
      else
        result_map[property_name]=string_value
      end
    end
    result_map

  end
  
  def get_relationship_node(field_name,filter_map,return_field=:id)
    unless @node_map.has_key? [field_name,return_field]
      node_spec = @format_config['fields'].find { |f| f['name']==field_name }
      clazz= node_spec['relationship_class']
      key=node_spec['relationship_key']
      position=node_spec['position']
      unless @index_map.has_key? clazz
        @index_map[clazz]=Index.new("/#{clazz}")
      end
      search_map={key=>@data[position]}.merge! filter_map
      hits=@index_map[clazz].find(search_map)
      raise "cross reference not found" if hits.size==0
      raise "duplicate cross references found" if hits.size>1

      @node_map[[field_name,return_field]]=hits[0][return_field]
    end
    return_field==:id ? @node_map[[field_name,return_field]].to_i : @node_map[[field_name,return_field]]
    
  end

  

end
